package com.czb.seckill.config;

import com.czb.seckill.pojo.User;
import com.czb.seckill.service.UserService;
import com.czb.seckill.util.CookieUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: 陈正彬
 * 自定义解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserService userService;

    //判断当前要解析的参数类型是不是需要的
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> aClass = methodParameter.getParameterType();
        return aClass == User.class;
    }

    //如果上面的方法返回true，就执行resolveArgument 方法
    //
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

//        HttpServletRequest request =webRequest.getNativeRequest(HttpServletRequest.class);
//        HttpServletResponse response =webRequest.getNativeResponse(HttpServletResponse.class);
//
//        String ticket = CookieUtil.getCookieValue(request, "userTicket");
//        if (!StringUtils.hasText(ticket)) {
//            return null;
//        }
//        //根据 cookie-ticket 到 Redis 获取 User
//        return userService.getUserByCookie(ticket, request, response);
        return UserContext.getUser();
    }
}
